<template>
    <div class="common-layout">
        <el-container>
            <el-header style="border-style: groove;border-width: 0px;margin-bottom: 12px;">
                <el-card style="height: 120px;">
                    <el-form :inline="true">
                        <el-form-item label="供应商" style="width: 220px;">
                            <el-input v-model="info.suppliercode" placeholder="请输入供应商名称/编号" />
                        </el-form-item>
                        <el-form-item label="状态" style="width: 210px;">
                            <el-select clearable v-model="info.supplierStatus">
                                <el-option label="启用" :value="0" />
                                <el-option label="禁用" :value="1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属行业" style="width: 220px;">
                            <el-select clearable v-model="info.industryId">
                                <el-option v-for="item in Industry" :label="item.industryName"
                                    :value="item.industryId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="进货负责人" style="width: 220px;">
                            <el-select clearable v-model="info.userid">
                                <el-option v-for="item in User" :label="item.userName" :value="item.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button  @click="Reset()">重置</el-button>
                            <el-button  type="primary" @click="GetSupplier">查询</el-button>
                            <el-button  @click="drawerVisible = true">高级搜索</el-button>
                        </el-form-item>


                        <el-form-item>

                            <el-button  type="success"
                                @click="router.push('/CreateSupplier')">新增</el-button>
                            <el-button type="danger" @click="detail">批量删除</el-button>
                            <el-button type="warning" @click="ExportSupplier">导出</el-button>
                            <el-button  @click="">导入</el-button>
                            <el-button type="primary" @click="refreshPage">刷新</el-button>
                            <el-button @click="showColumnSettings = true">表头设置</el-button>

                        </el-form-item>
                    </el-form>
                </el-card>
            </el-header>
            <el-main style="border-style: groove;border-width: 0px;margin-top: 7px;">
                <el-card style="margin-top: 30px;">
                    <el-table ref="multipleTableRef" :data="tableData" row-key="supplierId" 
                        style="width: 100%" border stripe @selection-change="handleSelectionChange" empty-text="暂无数据">
                        <el-table-column type="selection" :selectable="selectable" width="55" fixed="left" />
                        <el-table-column type="index" label="序号" width="60" fixed="left" />

                        <!-- 动态生成列 -->
                        <template v-for="column in visibleColumns" :key="column.key">
                            <!-- 供应商编码列 -->
                            <el-table-column v-if="column.key === 'supplierCode'" prop="supplierCode"
                                :label="column.label" width="140" :fixed="column.fixed ? 'left' : false" show-overflow-tooltip>
                                <template v-slot="scope">
                                    <el-link type="primary" @click="DetailSuppliers(scope.row)">
                                        {{ scope.row.supplierCode }}
                                    </el-link>
                                </template>
                            </el-table-column>

                            <!-- 供应商名称列 -->
                            <el-table-column v-else-if="column.key === 'supplierName'" prop="supplierName"
                                :label="column.label" :width="getColumnWidth(column.key)" 
                                :fixed="column.fixed ? 'left' : false" show-overflow-tooltip />

                            <!-- 所属行业列 -->
                            <el-table-column v-else-if="column.key === 'industryName'"
                                :label="column.label" :width="getColumnWidth(column.key)"
                                :fixed="column.fixed ? 'left' : false" show-overflow-tooltip>
                                <template v-slot="scope">
                                    {{ scope.row.industryName || industryNameMap[scope.row.industryId] || '--' }}
                                </template>
                            </el-table-column>

                            <!-- 供应商分类列 -->
                            <el-table-column v-else-if="column.key === 'supplierTypeName'"
                                :label="column.label" :width="getColumnWidth(column.key)"
                                :fixed="column.fixed ? 'left' : false" show-overflow-tooltip>
                                <template v-slot="scope">
                                    {{ scope.row.supplierTypeName || supplierTypeNameMap[scope.row.supplierTypeId] || '--' }}
                                </template>
                            </el-table-column>

                            <!-- 纳税人识别号列 -->
                            <el-table-column v-else-if="column.key === 'taxpayerNumber'" prop="taxpayerNumber"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip>
                                <template v-slot="scope">
                                    <span class="number-text">{{ scope.row.taxpayerNumber || '--' }}</span>
                                </template>
                            </el-table-column>

                            <!-- 银行账户列 -->
                            <el-table-column v-else-if="column.key === 'bankAccount'" prop="bankAccount"
                                :label="column.label" :width="getColumnWidth(column.key)" show-overflow-tooltip>
                                <template v-slot="scope">
                                    <span class="number-text">{{ scope.row.bankAccount || '--' }}</span>
                                </template>
                            </el-table-column>

                            <!-- 状态列 -->
                            <el-table-column v-else-if="column.key === 'supplierStatus'" prop="supplierStatus"
                                :label="column.label" width="100" :fixed="column.fixed ? 'left' : false">
                                <template v-slot="scope">
                                    <el-tag type="success" v-if="scope.row.supplierStatus == 0" size="small">启用</el-tag>
                                    <el-tag type="danger" v-if="scope.row.supplierStatus == 1" size="small">禁用</el-tag>
                                </template>
                            </el-table-column>

                            <!-- 操作人列 -->
                            <el-table-column v-else-if="column.key === 'createor'" prop="createor"
                                :label="column.label" width="100" :fixed="column.fixed ? 'left' : false">
                                <template v-slot="scope">
                                    {{ scope.row.createor || currentUserName }}
                                </template>
                            </el-table-column>

                            <!-- 操作时间列 -->
                            <el-table-column v-else-if="column.key === 'createrTime'" prop="createrTime"
                                :label="column.label" width="120" :fixed="column.fixed ? 'left' : false">
                                <template v-slot="scope">
                                    {{ scope.row.createrTime ? moment(scope.row.createrTime).format('YYYY-MM-DD') : currentTime }}
                                </template>
                            </el-table-column>

                            <!-- 普通列 -->
                            <el-table-column v-else :prop="column.key" :label="column.label"
                                :width="getColumnWidth(column.key)" :fixed="column.fixed ? 'left' : false" 
                                show-overflow-tooltip />
                        </template>

                        <el-table-column fixed="right" label="操作" width="140" align="center">
                            <template #default="scope">
                                <el-button link type="primary" size="small" @click="goEdit(scope.row)">编辑</el-button>
                                <el-button link type="danger" size="small"
                                    @click="SupplierDelete(scope.row.supplierId)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>

                </el-card>

            </el-main>

        </el-container>

    </div>
    <el-card style="margin-top: 15px;">
        <div class="pager-bar">
            <div class="pager-group">
                <el-button size="small" @click="goFirstPage" :disabled="page.pageindex <= 1">首页</el-button>
                <el-button size="small" @click="goPrevPage" :disabled="page.pageindex <= 1">上一页</el-button>
                <el-button size="small" @click="goNextPage" :disabled="page.pageindex >= page.pageCount">下一页</el-button>
                <el-button size="small" @click="goLastPage" :disabled="page.pageindex >= page.pageCount">尾页</el-button>
            </div>
            <el-pagination
                size="small"
                v-model:current-page="page.pageindex"
                v-model:page-size="page.pagesize"
                :page-sizes="[5, 10, 20, 30]"
                :background="true"
                layout="sizes, prev, pager, next, jumper"
                :total="page.listCount"/>
            <div class="pager-info">共 {{ page.listCount }} 条｜共 {{ page.pageCount }} 页｜当前第 {{ page.pageindex }} 页</div>
        </div>
    </el-card>

    <!-- 表头设置弹窗 -->
    <el-dialog v-model="showColumnSettings" title="表头设置" width="520px" :close-on-click-modal="false">
        <div class="column-settings">
            <div class="settings-header">
                <span>显示</span>
                <span>表头名称</span>
                <span>拖动排序</span>
            </div>

            <div class="column-list">
                <div v-for="(column, index) in allColumns" :key="column.key" class="column-item">
                    <div class="column-cell column-check">
                        <el-checkbox v-model="column.visible" />
                    </div>
                    <div class="column-cell column-name">
                        {{ column.label }}
                    </div>
                    <div class="column-cell column-actions">
                        <el-button size="small" text @click="moveColumn(index, -1)" :disabled="index === 0">↑</el-button>
                        <el-button size="small" text @click="moveColumn(index, 1)"
                            :disabled="index === allColumns.length - 1">↓</el-button>
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="resetColumnSettings">外观重置</el-button>
                <el-button @click="showColumnSettings = false">取消</el-button>
                <el-button type="primary" @click="saveColumnSettings">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <el-drawer title="高级搜索" v-model="drawerVisible" direction="rtl" size="30%">
        <el-row :gutter="20">
            <!-- 左列 -->
            <el-col :span="12">
                <el-form label-width="100px" class="search-form">
                    <el-form-item label="供应商编码">
                        <el-input v-model="info.suppliercode" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="所属行业">
                        <el-select placeholder="请选择">
                            <el-option label="选项1" value="1" />
                            <el-option label="选项2" value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="联系人">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="电子邮箱">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="进货负责人">
                        <el-input placeholder="请输入" />

                    </el-form-item>
                    <el-form-item label="供应商地址">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="纳税人识别号">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="开户银行">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="操作时间">
                        <el-select placeholder="请选择">
                            <el-option label="选项1" value="1" />
                            <el-option label="选项2" value="2" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-col>
            <!-- 右列 -->
            <el-col :span="12">
                <el-form label-width="100px" class="search-form">
                    <el-form-item label="供应商名称">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="供应商分类">
                        <el-select placeholder="请选择">
                            <el-option label="选项1" value="1" />
                            <el-option label="选项2" value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="联系电话">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="进货部门">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select placeholder="请选择">
                            <el-option label="启用" value="1" />
                            <el-option label="禁用" value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="账户名称">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="银行账户">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="操作人">
                        <el-input placeholder="请输入" />
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <div class="button-group">
            <el-button>重置</el-button>
            <el-button @click="drawerVisible = false">关闭</el-button>
            <el-button type="primary" @click=GetSupplier>查询</el-button>
        </div>
    </el-drawer>
</template>

<script lang="ts" setup>
import myaxios from '@/http/MyAxios';
import router from '@/router';
import axios from 'axios';
import { ElMessage, ElMessageBox, SCOPE } from 'element-plus';
import { da } from 'element-plus/es/locales.mjs';
import moment from 'moment';
import { reactive, ref, onMounted, watch, computed } from 'vue';
// 表头设置相关
const showColumnSettings = ref(false)

// 获取当前登录用户和当前时间
const currentUserName = ref('')
const currentTime = computed(() => {
    return moment().format('YYYY-MM-DD')
})

// 从后端获取当前登录用户的真实姓名
const loadCurrentUser = async () => {
    try {
        const res = await myaxios.get('/api/User/GetMyProfile')
        const droot: any = res?.data ?? {}
        const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
        if (d) {
            // 优先使用真实姓名，其次用户名，最后账号
            currentUserName.value = d.userName || d.realName || d.nickname || localStorage.getItem('username') || ''
            // 如果获取到了，更新localStorage
            if (currentUserName.value) {
                localStorage.setItem('username', currentUserName.value)
            }
        } else {
            // 如果接口失败，使用localStorage中的值
            currentUserName.value = localStorage.getItem('username') || ''
        }
    } catch (error) {
        // 如果接口失败，使用localStorage中的值
        console.warn('获取当前用户信息失败，使用本地存储的值:', error)
        currentUserName.value = localStorage.getItem('username') || ''
    }
}

// 定义列类型
interface ColumnConfig {
    key: string
    label: string
    visible: boolean
    fixed: boolean
}

// 定义所有可用的列
const allColumns = ref<ColumnConfig[]>([
    { key: 'supplierCode', label: '供应商编码', visible: true, fixed: true },
    { key: 'supplierName', label: '供应商', visible: true, fixed: true },
    { key: 'industryName', label: '所属行业', visible: true, fixed: false },
    { key: 'supplierTypeName', label: '供应商分类', visible: true, fixed: false },
    { key: 'contact', label: '联系人', visible: true, fixed: false },
    { key: 'contactNumber', label: '联系电话', visible: true, fixed: false },
    { key: 'supplierEmail', label: '电子邮箱', visible: true, fixed: false },
    { key: 'organizationName', label: '进货部门', visible: true, fixed: false },
    { key: 'userName', label: '进货负责人', visible: true, fixed: false },
    { key: 'supplierStatus', label: '状态', visible: true, fixed: false },
    { key: 'supplierAddress', label: '供应商地址', visible: true, fixed: false },
    { key: 'financeName', label: '账户名称', visible: true, fixed: false },
    { key: 'taxpayerNumber', label: '纳税人识别号', visible: true, fixed: false },
    { key: 'bankAccount', label: '银行账户', visible: true, fixed: false },
    { key: 'accountBank', label: '开户银行', visible: true, fixed: false },
    { key: 'bankAddress', label: '开户行地址', visible: true, fixed: false },
    { key: 'createor', label: '操作人', visible: true, fixed: false },
    { key: 'createrTime', label: '操作时间', visible: true, fixed: false },
])

// 计算显示的列
const visibleColumns = computed<ColumnConfig[]>(() => {
    return allColumns.value.filter(col => col.visible)
})

// 保存列设置
const saveColumnSettings = () => {
    localStorage.setItem('supplierTableColumns', JSON.stringify(allColumns.value))
    showColumnSettings.value = false
    ElMessage.success('表头设置已保存')
}

// 重置列设置
const resetColumnSettings = () => {
    allColumns.value.forEach(col => {
        col.visible = true
        col.fixed = ['supplierCode', 'supplierName'].includes(col.key)
    })
}

// 获取列宽度
const getColumnWidth = (key: string) => {
    const widthMap: Record<string, number> = {
        supplierName: 160,
        industryName: 120,
        supplierTypeName: 120,
        contact: 100,
        contactNumber: 130,
        supplierEmail: 180,
        organizationName: 120,
        userName: 120,
        supplierAddress: 200,
        financeName: 150,
        taxpayerNumber: 160,
        bankAccount: 180,
        accountBank: 150,
        bankAddress: 200,
        createor: 100,
    }
    return widthMap[key] || 120
}

// 移动列位置
const moveColumn = (index: number, direction: number) => {
    const newIndex = index + direction
    if (newIndex >= 0 && newIndex < allColumns.value.length) {
        const columns: ColumnConfig[] = [...allColumns.value]
        const temp = columns[index]
        if (temp && columns[newIndex]) {
            columns[index] = columns[newIndex]
            columns[newIndex] = temp
            allColumns.value = columns
        }
    }
}

// 加载列设置
const loadColumnSettings = () => {
    const saved = localStorage.getItem('supplierTableColumns')
    if (saved) {
        try {
            const savedColumns: ColumnConfig[] = JSON.parse(saved)
            if (Array.isArray(savedColumns) && savedColumns.length === allColumns.value.length) {
                const isValid = savedColumns.every(col =>
                    col &&
                    typeof col.key === 'string' &&
                    typeof col.label === 'string' &&
                    typeof col.visible === 'boolean' &&
                    typeof col.fixed === 'boolean'
                )
                if (isValid) {
                    allColumns.value = savedColumns
                }
            }
        } catch (error) {
            console.warn('Failed to load supplier column settings:', error)
        }
    }
}

//供应商参数
const info = reactive({
    suppliercode: '',
    supplierStatus: '',
    industryId: '',
    userid: '',
})
//分页
const page = reactive({
    pageindex: 1,
    pagesize: 10,
    listCount: 0,
    pageCount: 0
})
//抽屉显示状态
const drawerVisible = ref(false)
//重置
const Reset = () => {
    info.industryId = ''
    info.supplierStatus = ''
    info.userid = ''
    info.suppliercode = ''
}

// 加载状态
const loading = ref(false)

//供应商数据源
const tableData = ref<any[]>([])
const enrichSupplierRow = (row: any) => {
    if (!row) return row
    const industryKey = row.industryId !== undefined && row.industryId !== null ? String(row.industryId) : ''
    const supplierTypeKey = row.supplierTypeId !== undefined && row.supplierTypeId !== null ? String(row.supplierTypeId) : ''
    return {
        ...row,
        industryName: row.industryName || (industryKey ? industryNameMap.value[industryKey] || '' : ''),
        supplierTypeName: row.supplierTypeName || (supplierTypeKey ? supplierTypeNameMap.value[supplierTypeKey] || '' : '')
    }
}
const GetSupplier = () => {
    loading.value = true
    myaxios.get('/api/Supplier/GetSupplier', {
        params: {
            suppliercode: info.suppliercode, //供应商名称/编号
            supplierStatus: info.supplierStatus, //状态
            industryId: info.industryId, //行业
            userId: info.userid, //进货负责人
            pageindex: page.pageindex, //页码
            pagesize: page.pagesize //每页条数   
        }
    }).then(res => {
        const list = res.data?.data?.data || []
        tableData.value = list.map((item: any) => enrichSupplierRow(item));
        page.listCount = res.data.data.listCount;
        page.pageCount = res.data.data.pageCount;
    }).catch(err => {
        console.error('获取供应商列表失败:', err)
        ElMessage.error('获取供应商列表失败')
    }).finally(() => {
        loading.value = false
    })
}

// 刷新当前页面
const refreshPage = () => {
    window.location.reload()
}

// 跳转编辑
const goEdit = (row: any) => {
    router.push({
        path: '/UpdateSupplier',
        query: { supplierId: row.supplierId }
    })
}
//行业下拉框
const Industry: any = ref([]);
const GetIndustry = () => {
    myaxios.get('api/Supplier/GetIndustry').then(res => {
        if (res.data?.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
            Industry.value = res.data.data;
        }
    })
}
const loadIndustryList = async () => {
    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    if (children.length > 0) {
        Industry.value = children.map((item: any) => ({
            industryId: item.dictionaryId,
            industryName: item.dictionaryName
        }))
    }
}
const industryNameMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    const list = Array.isArray(Industry.value) ? Industry.value : []
    list.forEach((item: any) => {
        const id = item?.industryId ?? item?.dictionaryId
        if (id !== undefined && id !== null) {
            map[String(id)] = item?.industryName ?? item?.dictionaryName ?? ''
        }
    })
    return map
})

// 供应商分类字典
interface SupplierTypeItem { supplierTypeId: string | number; supplierTypeName: string }
const supplierTypeList = ref<SupplierTypeItem[]>([])
const supplierTypeNameMap = computed<Record<string, string>>(() => {
    const map: Record<string, string> = {}
    supplierTypeList.value.forEach(item => {
        if (item.supplierTypeId !== undefined && item.supplierTypeId !== null) {
            map[String(item.supplierTypeId)] = item.supplierTypeName || ''
        }
    })
    return map
})

const isRootDictionary = (item: any) =>
    !item?.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item?.dictionaryName || '').toLowerCase()
    const code = (item?.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const params = { Pageindex: 1, PageSize: 1000 }
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
        const list = res.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadSupplierTypeList = async () => {
    const parentId = await findDictionaryParentId(['供应商分类', '供应商类型'], ['suppliertype', 'supplier_type'])
    const children = await fetchDictionaryChildren(parentId)
    supplierTypeList.value = children.map((item: any) => ({
        supplierTypeId: item.dictionaryId,
        supplierTypeName: item.dictionaryName
    }))
}

//用户下拉框
const User: any = ref([]);
const GetUser = () => {
    myaxios.get('api/Supplier/GetUser').then(res => {
        User.value = res.data.data;

    })
}
watch(page, () => {
    GetSupplier();
})

watch([Industry, supplierTypeList], () => {
    tableData.value = tableData.value.map((item: any) => enrichSupplierRow(item))
})
onMounted(() => {
    GetSupplier(); //获取供应商数据
    GetIndustry(); //获取行业数据（接口）
    loadIndustryList(); //加载行业字典
    GetUser(); //获取用户数据
    loadSupplierTypeList(); //获取供应商分类字典
    loadColumnSettings(); //加载列设置
    loadCurrentUser(); //获取当前登录用户信息
})


const SupplierDelete = (supplierid: any) => {
    ElMessageBox.confirm(
        '确认删除该条数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )

        .then(() => {
            axios.put('http://localhost:8080/api/Supplier/DeleteSupplier?supplierid=' + supplierid).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetSupplier(); //获取供应商数据

                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '供应商删除已取消!',
            })
        })
}
//批量删除
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const multipleTableRef = ref()
const multipleSelection = ref([])
const selectable = (row: any) => ![1, 2].includes(row.id)
const detail = (supplierid: any) => {
    if (multipleSelection.value.length == 0) {
        ElMessage.error('请选择要删除的供应商')
        return;
    }
    ElMessageBox.confirm(
        '确认删除该条数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )

        .then(() => {
            axios.put('http://localhost:8080/api/Supplier/DeleteAllSupplier?supplierids=' + multipleSelection.value.map((item: any) => item.supplierId)).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetSupplier(); //获取供应商数据

                }
                else {
                    ElMessage.error(res.data.message);
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '供应商删除已取消!',
            })
        })
}
const DetailSuppliers = (row: any) => {
    router.push({
        path: '/DetailSupplier',
        query: {
            "supplierId": row.supplierId,
            "supplierCode": row.supplierCode,
            "supplierName": row.supplierName,
            "industryId": row.industryId,
            "industryName": row.industryName,
            "supplierTypeId": row.supplierTypeId,
            "supplierTypeName": row.supplierTypeName,
            "contact": row.contact,
            "contactNumber": row.contactNumber,
            "supplierEmail": row.supplierEmail,
            "organizationId": row.organizationId,
            "organizationName": row.organizationName,
            "userId": row.userId,
            "userName": row.userName,
            "supplierStatus": row.supplierStatus,
            "supplierAddress": row.supplierAddress,
            "financeId": row.financeId,
            "financeName": row.financeName,
            "taxpayerNumber": row.taxpayerNumber,
            "bankAccount": row.bankAccount,
            "accountBank": row.accountBank,
            "bankAddress": row.bankAddress,
            "createor": row.createor,
            "createrTime": row.createrTime
        }
    })
}

// 导出供应商（按当前筛选与分页）
const ExportSupplier = () => {
    if (multipleSelection.value && multipleSelection.value.length > 0) {
        const headers = [
            '供应商编码', '供应商名称', '行业', '分类', '联系人', '联系电话', '邮箱', '部门', '负责人', '状态', '地址', '账户名称', '纳税人识别号', '银行账户', '开户银行', '开户行地址', '创建人', '创建时间'
        ];
        const rows = multipleSelection.value.map((x: any) => [
            x.supplierCode ?? '',
            x.supplierName ?? '',
            x.industryName ?? '',
            x.supplierTypeName ?? '',
            x.contact ?? '',
            x.contactNumber ?? '',
            x.supplierEmail ?? '',
            x.organizationName ?? '',
            x.userName ?? '',
            (x.supplierStatus === 0 ? '启用' : '禁用'),
            x.supplierAddress ?? '',
            x.financeName ?? '',
            x.taxpayerNumber ?? '',
            x.bankAccount ?? '',
            x.accountBank ?? '',
            x.bankAddress ?? '',
            (x.createor ?? ''),
            (x.createrTime ? moment(x.createrTime).format('YYYY-MM-DD HH:mm:ss') : '')
        ]);
        const escape = (v: any) => {
            const s = String(v).replace(/"/g, '""');
            return /[",\n]/.test(s) ? `"${s}"` : s;
        };
        const csv = [headers.map(escape).join(','), ...rows.map(r => r.map(escape).join(','))].join('\n');
        const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.download = `供应商_已选_${moment().format('YYYYMMDDHHmmss')}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        ElMessage.success('已导出所选数据');
        return;
    }
    myaxios.get('/api/Supplier/ExportSupplier', {
        params: {
            suppliercode: info.suppliercode,
            supplierStatus: info.supplierStatus,
            industryId: info.industryId,
            userid: info.userid,
            pageindex: page.pageindex,
            pagesize: page.pagesize
        },
        responseType: 'blob'
    }).then((res: any) => {
        const disposition = res.headers?.['content-disposition'] || res.headers?.['Content-Disposition'];
        let fileName = `供应商_${moment().format('YYYYMMDDHHmmss')}.xlsx`;
        if (disposition) {
            const match = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(disposition);
            if (match) {
                const raw = (match[1] ?? match[2]);
                if (typeof raw === 'string' && raw.length > 0) {
                    fileName = decodeURIComponent(raw);
                }
            }
        }

        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        ElMessage.success('导出成功');
    }).catch((err: any) => {
        console.error(err);
        ElMessage.error('导出失败');
    })
}

const goFirstPage = () => {
    if (page.pageindex > 1) {
        page.pageindex = 1
    }
}

const goPrevPage = () => {
    if (page.pageindex > 1) {
        page.pageindex -= 1
    }
}

const goNextPage = () => {
    if (page.pageindex < page.pageCount) {
        page.pageindex += 1
    }
}

const goLastPage = () => {
    if (page.pageCount > 0 && page.pageindex < page.pageCount) {
        page.pageindex = page.pageCount
    }
}

</script>

<style scoped>
.pager-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
}
.pager-group {
  display: flex;
  align-items: center;
  gap: 8px;
}
.pager-info {
  color: #666;
  white-space: nowrap;
  font-size: 12px;
}

/* 表头设置样式优化 */
.column-settings {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.settings-header {
  display: grid;
  grid-template-columns: 80px 1fr 120px;
  padding: 6px 12px;
  font-size: 13px;
  color: #909399;
  border-bottom: 1px solid #ebeef5;
}

.column-list {
  max-height: 360px;
  overflow-y: auto;
  border-radius: 4px;
}

.column-item {
  display: grid;
  grid-template-columns: 80px 1fr 120px;
  align-items: center;
  padding: 6px 12px;
  font-size: 13px;
  border-bottom: 1px solid #f2f2f2;
}

.column-item:last-child {
  border-bottom: none;
}

.column-item:hover {
  background-color: #f5f7fa;
}

.column-cell {
  display: flex;
  align-items: center;
}

.column-check {
  justify-content: center;
}

.column-name {
  color: #303133;
}

.column-actions {
  justify-content: flex-start;
  gap: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 表格优化样式 */
:deep(.el-table) {
    font-size: 13px;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    padding: 12px 0;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafafa;
}

:deep(.el-table .el-table__row:hover > td) {
    background-color: #f5f7fa !important;
}

/* 数字文本样式 */
.number-text {
    font-family: 'Courier New', monospace;
    letter-spacing: 0.5px;
    color: #303133;
}

/* 链接样式优化 */
:deep(.el-link) {
    font-weight: 500;
}

/* 标签样式优化 */
:deep(.el-tag) {
    border-radius: 4px;
    font-weight: 500;
}

/* 表格边框优化 */
:deep(.el-table--border) {
    border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
    border-right: 1px solid #ebeef5;
}

/* 固定列阴影 */
:deep(.el-table__fixed),
:deep(.el-table__fixed-right) {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.12);
}

/* 表格卡片样式 */
.el-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 优化表格滚动条 */
:deep(.el-table__body-wrapper) {
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f1f1f1;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 8px;
    height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #f1f1f1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background: #c1c1c1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
    background: #a8a8a8;
}

/* 操作按钮样式 */
:deep(.el-table .el-button--link) {
    padding: 4px 8px;
    margin: 0 4px;
    font-weight: 500;
}

:deep(.el-table .el-button--link:hover) {
    text-decoration: underline;
}

/* 筛选表单样式优化 */
:deep(.el-form--inline .el-form-item) {
    margin-bottom: 16px;
}
</style>
